package com.edu.yunnote;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.edu.yunnote.dto.Note;
import com.edu.yunnote.dto.WebResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ShowActivity extends AppCompatActivity {

    private Button btnSave;
    private Button btnCancel;
    private TextView showTime;
    private TextView showNoteId;
    private EditText showContent;
    private EditText showTitle;

    private Note note;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_show);

        init();
    }

    public void init() {
        btnCancel = findViewById(R.id.show_cancel);
        btnSave = findViewById(R.id.show_save);
        showTime = findViewById(R.id.show_time);
        showTitle = findViewById(R.id.show_title);
        showContent = findViewById(R.id.show_content);
        showNoteId = findViewById(R.id.show_note_id);

        Intent intent = this.getIntent();
        if (intent != null) {
            note = new Note();

            note.setNoteTitle(intent.getStringExtra("noteTitle"));
            note.setNoteContent(intent.getStringExtra("noteContent"));
            note.setNoteTime(intent.getStringExtra("noteTime"));
            note.setNoteId(Integer.parseInt(intent.getStringExtra("noteId")));
            //显示原来的数据
            showTime.setText(note.getNoteTime());
            showTitle.setText(note.getNoteTitle());
            showContent.setText(note.getNoteContent());
            showNoteId.setText(note.getNoteId().toString());
        }

        //按钮点击事件
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = showContent.getText().toString();
                String title = showTitle.getText().toString();
                String noteId = showNoteId.getText().toString();

                String url = getString(R.string.url) + "/noteServlet";
                Map<String, Object> map = new HashMap<String, Object>();

                map.put("noteId",noteId);
                map.put("noteContent",content);
                map.put("noteTime",getTime());
                map.put("noteTitle",title);
                map.put("act", "edit");
                try {
                    postJSON(url , map , 1);
                } catch (IOException e) {
                    e.printStackTrace();
                    Log.d("LOOKUP  postJSON : ", e.getMessage());
                }

            }
        });

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String content = showContent.getText().toString();
                final String title = showTitle.getText().toString();
                new AlertDialog.Builder(ShowActivity.this)
                        .setTitle("提示框")
                        .setMessage("是否保存当前内容?")
                        .setPositiveButton("yes",
                                new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String content = showContent.getText().toString();
                                String title = showTitle.getText().toString();
                                String noteId = showNoteId.getText().toString();

                                String url = getString(R.string.url) + "/noteServlet";
                                Map<String, Object> map = new HashMap<String, Object>();

                                map.put("noteId",noteId);
                                map.put("noteContent",content);
                                map.put("noteTime",getTime());
                                map.put("noteTitle",title);
                                map.put("act", "edit");
                                try {
                                    postJSON(url , map , 1);
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    Log.d("LOOKUP  postJSON : ", e.getMessage());
                                }
                            }
                        })
                        .setNegativeButton("no",
                                new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                gotoActivity(MainActivity.class);
                            }
                        }).show();
            }
        });
    }

    //获取当前时间
    private String getTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        String str = sdf.format(date);
        return str;
    }
    /**
     * intent跳转页面，不能返回之前页面
     * @param B
     */
    private void gotoActivity(Class B){
        Intent intent=new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setClass(ShowActivity.this, B);
        startActivity(intent);
    }

    /**
     * ==============================OKHTTP请求 ==============================================
     */
    /**
     * 当前类的消息机制 手柄，句柄
     */
    private Handler handler = new Handler(new Handler.Callback() { //消息回调
        @Override
        public boolean handleMessage(Message msg) {
            Map<String, Object> parmaData = new HashMap<String, Object>();
            WebResponse webResponse;
            String res = null;
            switch(msg.what){
                case 1:     //修改笔记
                    res = msg.obj.toString();
                    Log.d("LOOKUP -- Response : ", res); //请求数据在msg.obj.toString()中

                    if(res.indexOf("HTTP Status") != -1){
                        Toast.makeText(ShowActivity.this,"网络请求出错" ,Toast.LENGTH_SHORT).show();
                        break;
                    }
                    //把json数据转换成webResponse
                    webResponse = new Gson().fromJson(res, WebResponse.class);
                    Log.d("LOOKUP webResponse : ", webResponse.toString());

                    if(webResponse.getStatusCode() == 200) {
                        Toast.makeText(ShowActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(ShowActivity.this,webResponse.getStatusMsg() ,Toast.LENGTH_LONG).show();
                        break;
                    }
                    gotoActivity(MainActivity.class);
                    break;
                default:
                    Toast.makeText(ShowActivity.this,"网络服务器连接失败" ,Toast.LENGTH_SHORT).show();
                    break;
            }
            return true;
        }
    });

    /**
     *
     * @param url 请求地址
     * @param map 转化成 json字符串作为请求参数
     * @param msgWhat 发送消息的编号，用于接收消息时判断
     * @return
     * @throws IOException
     */
    public void postJSON(String url , Map<String, Object> map , final Integer msgWhat) throws IOException {

        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
        String json = gson.toJson(map);
        OkHttpClient client = new OkHttpClient();
        MediaType JSON   = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Call call  = client.newCall(request);
        call.enqueue(new Callback(){
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
                Log.d("LOOKUP","请求失败");
                Log.d("LOOKUP",e.getMessage());
                Message msg = new Message();
                msg.obj = "网络服务器连接失败";
                msg.what = 0;
                handler.sendMessage(msg);	//发送消息到句柄

            }
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Message msg = new Message();
                msg.obj = response.body().string();
                msg.what = msgWhat;
                handler.sendMessage(msg);	//发送消息到句柄
            }
        });
    }
    /**
     * ==============================OKHTTP请求 end==============================================
     */
}
